package com.tumanex.socialshare;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;

/**
 * 
 * @author artemka
 * 
 */
public class SitesApp {

	private Context mContext;

	ParseResponse parsePesponse;

	HashMap<String, String> params;

	private Session mSession;

	public SitesApp(Context context) {

		mContext = context;

		mSession = new Session(mContext);

		parsePesponse = new ParseResponse();
	}

	public boolean hasAccessToken() {

		String[] params = mSession.getAccessToken();

		if (params != null) {

			long accessTime = Long.parseLong(params[3]);
			long currentTime = System.currentTimeMillis();
			long expireTime = (currentTime - accessTime) / 1000;

			if (params[0].equals("") & params[1].equals("")
					& params[2].equals("") & Long.parseLong(params[3]) == 0) {

				return false;

			} else if (expireTime >= Long.parseLong(params[1])) {

				return false;

			} else {

				return true;

			}
		}
		return false;
	}

	public void saveAccessToken(String accessToken, String expires,
			String userId) {

		mSession.saveAccessToken(accessToken, expires, userId);
	}

	public void resetAccessToken() {

		mSession.resetAccessToken();
	}

	public String[] parseUrlParams(String url) {

		String[] query = url.split("#");
		String[] params = query[1].split("&");

		return params;
	}

	public boolean postToVkWall(String message) {

		String[] paramsMethod = mSession.getAccessToken();

		String accessToken = paramsMethod[0];
		String ownerId = paramsMethod[2];

		JSONObject jsonObj;

		String url;

		if (message.equals("")) {
			url = ConstantsApp.VK_POST_TO_WALL_URL + "owner_id=" + ownerId
					+ "&attachments=" + params.get("id") + "&access_token="
					+ accessToken;
		} else {
			url = ConstantsApp.VK_POST_TO_WALL_URL + "owner_id=" + ownerId
					+ "&message=" + Uri.encode(message) + "&attachments="
					+ params.get("id") + "&access_token=" + accessToken;
		}

		try {

			jsonObj = new JSONObject(sendRequest(url));

			if (parsePesponse.parseErrorCode(jsonObj) != -1) {
				return false;
			}

			parsePesponse.parseVkWallPost(jsonObj);

		} catch (JSONException e) {
		}

		return true;
	}

	public boolean VkSaveWallPhoto() {

		String[] paramsMethod = mSession.getAccessToken();

		String accessToken = paramsMethod[0];

		@SuppressWarnings("deprecation")
		String server = URLEncoder.encode(params.get("server"));
		@SuppressWarnings("deprecation")
		String photo = URLEncoder.encode(params.get("photo"));
		@SuppressWarnings("deprecation")
		String hash = URLEncoder.encode(params.get("hash"));

		JSONObject jsonObj;
		try {

			jsonObj = new JSONObject(
					sendRequest(ConstantsApp.VK_SAVE_WALL_PHOTO + "server="
							+ server + "&photo=" + photo + "&hash=" + hash
							+ "&access_token=" + accessToken));

			if (parsePesponse.parseErrorCode(jsonObj) != -1) {
				return false;
			}

			params = parsePesponse.parseVkSaveWallPhoto(jsonObj);

		} catch (JSONException e) {
		}

		return true;
	}

	public boolean getWallUploadVkServer() {

		String[] paramsMethod = mSession.getAccessToken();

		String accessToken = paramsMethod[0];
		String ownerId = paramsMethod[2];

		JSONObject jsonObj;
		try {

			jsonObj = new JSONObject(
					sendRequest(ConstantsApp.VK_GET_UPLOAD_SERVER + "uid="
							+ ownerId + "&access_token=" + accessToken));
			if (parsePesponse.parseErrorCode(jsonObj) != -1) {
				return false;
			}

			params = parsePesponse.parseVkWallUploadServer(jsonObj);

		} catch (JSONException e) {
		}

		return true;
	}

	public String sendRequest(String url) {

		String responseText = null;

		HttpClient client = new DefaultHttpClient();

		HttpGet request = new HttpGet(url);

		try {

			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();

			responseText = EntityUtils.toString(entity);

		} catch (ClientProtocolException cexc) {

		} catch (IOException ioex) {
		}

		return responseText;
	}

	public boolean uploadImage(String serverUrl, Bitmap bitmap) {

		String sBuf;
		StringBuilder resp = new StringBuilder();

		try {

			HttpClient httpClient = new DefaultHttpClient();
			httpClient.getParams().setParameter(
					CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

			HttpPost postRequest = new HttpPost(serverUrl);

			ByteArrayOutputStream bos = new ByteArrayOutputStream();

			Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480,
					true);

			bmpCompressed.compress(CompressFormat.JPEG, 100, bos);

			byte[] data = bos.toByteArray();

			MultipartEntity reqEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);

			reqEntity.addPart("photo", new ByteArrayBody(data, "image/png"));

			postRequest.setEntity(reqEntity);

			HttpResponse response = httpClient.execute(postRequest);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));

			while ((sBuf = reader.readLine()) != null) {
				resp.append(sBuf);
			}

			JSONObject jsonObj = new JSONObject(resp.toString());

			if (parsePesponse.parseErrorCode(jsonObj) != -1) {
				return false;
			}

			params = parsePesponse.parseExecuteMultipartPost(jsonObj);

		} catch (Exception e) {
		}

		return true;
	}

	public HashMap<String, String> getResponseParams() {
		return params;
	}

}